package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.utils.TimeLineService;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class MovementApiImpl implements MovementApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private TimeLineService timeLineService;

    @Override
    public String save(Movement movement) {
        //1、保存动态详情
        mongoTemplate.save(movement);
        //使用多线程处理。
        //2、根据userId查询当前用户的所有好友
        Long userId = movement.getUserId();
        timeLineService.saveTimeline(userId,movement.getId());
        return movement.getId().toString();
    }

    //根据用户id，分页查询动态
    public List<Movement> findByUserId(Integer page, Integer pagesize, Long userId) {
        //1、创建Criteria
        Criteria criteria = Criteria.where("userId").is(userId);
        //2、创建Query，设置分页参数
        Query query = Query.query(criteria)
                .with(Sort.by(Sort.Order.desc("created")))
                .skip((page - 1) * pagesize)
                .limit(pagesize);
        //3、查询
        return mongoTemplate.find(query,Movement.class);
    }

    //根据好友id，分页查询好友动态列表（可见的动态列表）
    public List<Movement> findByFriendId(Integer page, Integer pagesize, Long friendId) {
        //1、分页查询时间线表
        Criteria lineCriteria = Criteria.where("friendId").is(friendId);
        Query lineQuery = Query.query(lineCriteria)
                .with(Sort.by(Sort.Order.desc("created")))
                .skip((page - 1) * pagesize)
                .limit(pagesize);
        List<MovementTimeLine> timeLines = mongoTemplate.find(lineQuery, MovementTimeLine.class);
        //2、从timeLines中提取所有的动态id
        List<ObjectId> movementIds = CollUtil.getFieldValues(timeLines, "movementId",
                    ObjectId.class);
        //3、根据所有动态id，查询动态的列表数据
        Criteria movementCriteria = Criteria.where("id").in(movementIds).and("state").is(1);//查询动态为1的   只有是1的才合法
        Query query = Query.query(movementCriteria);
        return mongoTemplate.find(query,Movement.class);
    }

    /**
     * 聚合查询：统计（总数，总金额..,采样）
     *          采样：从所有中随机获取一定的数据
     *
     */
    //随机查询动态详情
    //通过统计函数，实现随机查询
    public List<Movement> randomMovement(Integer count) {
        //指定聚合查询的，查询方式
        TypedAggregation<Movement> aggregation =
                        TypedAggregation.
                            newAggregation(Movement.class,Aggregation.sample(count));
        //查询统计结果
        AggregationResults<Movement> results = mongoTemplate.aggregate(aggregation, Movement.class);

        //从统计结果中获取真实统计数据
        return results.getMappedResults();
    }

    //根据动态id列表分页查询
    public List<Movement> findByIds(String[] movementIds, Integer page, Integer pagesize) {
        Criteria criteria = Criteria.where("id").in(movementIds);
        Query query = Query.query(criteria).skip((page - 1) * pagesize).limit(pagesize);
        List<Movement> list = mongoTemplate.find(query, Movement.class);
        return list;
    }

    //根据id查询
    @Override
    public Movement findById(String movementId) {
        return mongoTemplate.findById(new ObjectId(movementId),Movement.class);
    }

    //根据id去更新动态状态
    @Override
    public void updateState(String movementId, Integer state) {
        //update movement set state = ？ where id=？
        Query query = Query.query(Criteria.where("id").is(new ObjectId(movementId)));
        Update update = new Update();
        update.set("state",state);
        mongoTemplate.updateFirst(query,update,Movement.class);
    }
    /**
     * 查询单条动态
     */
    public Movement findOneMovements(String movementId) {
        return mongoTemplate.findById(new ObjectId(movementId), Movement.class);
    }
    //分页查询动态列表
    @Override
    public PageResult findAll(Integer state, Long userId, Integer page, Integer pagesize) {
        //1、构造Criteria
        Criteria criteria = new Criteria();
        if(state != null) {
            criteria.and("state").is(state);
        }
        if(userId != null) {
            criteria.and("userId").is(userId);
        }
        //2、创建Query
        Query query = Query.query(criteria);
        //3、总数
        long count = mongoTemplate.count(query, Movement.class);
        //4、分页参数设置
        query.with(Sort.by(Sort.Order.desc("created")))
                .skip((page-1) * pagesize)
                .limit(pagesize);
        //5、查询分页list列表
        List<Movement> list = mongoTemplate.find(query, Movement.class);
        return new PageResult(page,pagesize,count,list);
    }

}
